﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace nExt.Core.Helper
{
	/// <summary>
	/// Path für Web
	/// </summary>
	public static class WebPath
	{
		/// <summary>
		/// Erweitert die übergebene uri mit weiteren Pfad segmenten
		/// </summary>
		public static Uri Append(this Uri uri, bool shouldEndWithSlash, params string[] segments)
		{
			return new Uri(EnsureSlash(Combine(uri.ToString(), segments), shouldEndWithSlash));
		}

		/// <summary>
		/// Erweitert die übergebene uri mit weiteren Pfad segmenten
		/// </summary>
		public static Uri Append(this Uri uri, params string[] segments)
		{
			return new Uri(Combine(uri.ToString(), segments));
		}

		/// <summary>
		/// Fügt einen Parameter zu einer Url hinzu
		/// </summary>
		public static string AddParameterToUrl(string url, string key, string value)
		{
			if (!url.Contains(key + "="))
			{
				if (url.Contains("?") || url.Contains("%3F"))
					url += "&" + key + "=" + value;
				else
					url += "?" + key + "=" + value;
			}
			return url;
		}

		/// <summary>
		/// Fügt einen Parameter zu einer Url hinzu
		/// </summary>
		public static Uri AddParameter(this Uri uri, string key, string value)
		{
			return new Uri(AddParameterToUrl(uri.AbsoluteUri, key, value));
		}


		/// <summary>
		/// Fügt einen Parameter zu einer Url hinzu
		/// </summary>
		public static Uri AddParameter(this Uri uri, IDictionary<string,string> parameters)
		{
			return parameters.Aggregate(uri, (current, p) => new Uri(AddParameterToUrl(current.AbsoluteUri, p.Key, p.Value)));
		}

		/// <summary>
		/// Web Pfad combine
		/// </summary>
		public static string Combine(string path, params string[] segments)
		{
			var list = new List<string> { path };
			list.AddRange(segments);
			return Combine(list.ToArray());
		}

		/// <summary>
		/// Web Pfad combine
		/// </summary>
		/// <param name="segments">The path.</param>
		/// <returns></returns>
		public static string Combine(params string[] segments)
		{
			var sb = new StringBuilder();

			for (int index = 0; index < segments.Length; index++)
			{
				var p = segments[index];
				if (index == segments.Length - 1 && p.Contains("."))
					sb.Append(p);
				else
					sb.Append(EnsureSlash(p));
			}
			return sb.ToString();
		}

		/// <summary>
		/// Web Pfad combine
		/// </summary>
		public static string EnsureSlash(string path, bool shouldEndWithSlash = true)
		{
			if (!path.EndsWith("/"))
				path += "/";
			if (!shouldEndWithSlash)
				path = path.Substring(0, path.Length - 1);
			return path;
		}
	}
}